package Controller.Goods;


import Dto.Goods;
import Service.GoodsService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.sql.SQLException;
import java.time.LocalDateTime;

@MultipartConfig
@WebServlet(name = "updateGoods", value = "/updateGoods")
public class UpdateGoods extends HttpServlet {
    GoodsService goodsService = new GoodsService();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        Part filePart = request.getPart("img");
        String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString();
        String uploadDirectory = getServletContext().getRealPath("\\")+"webapp\\upload\\";
        File uploadDir = new File(uploadDirectory);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }
        String filePath = uploadDirectory  + fileName;
        filePart.write(filePath);

        String category = request.getParameter("goodscategory");
        String name = request.getParameter("name");
        String description = request.getParameter("discribe");
        String img = "/upload/"+fileName;
        String price = request.getParameter("oldprice");
        String selling = request.getParameter("newprice");
        String sales = request.getParameter("salenumber");
        String inventory = request.getParameter("inventory");
        String state = request.getParameter("status");
        LocalDateTime nowDate = LocalDateTime.now();
        Integer id = Integer.valueOf(request.getParameter("id"));
        Goods goods = new Goods();
        goods.setGoodscategory(category);
        goods.setName(name);
        goods.setDescribe(description);
        goods.setPicture(img);
        goods.setOldprice(price);
        goods.setNewprice(selling);
        goods.setSalenumber(sales);
        goods.setInventory(inventory);
        goods.setStatus(state);
        goods.setAddtime(nowDate.toString());
        goods.setId(id);
        try {
            goodsService.updateGoods(goods);
            request.getRequestDispatcher("/ListGoods").forward(request,response);
        }catch (SQLException e){
            e.printStackTrace();
        }
    }
}